#include "ota_http_curl.h"
#include "curl/curl.h"
#include <stdlib.h>
#include <string.h>


static size_t ota_http_curl_cb(char *data, size_t size, size_t nmemb, void *clientp)
{
    //1  强转
    response_body_t *response_body = (response_body_t *)clientp;
    //2  计算大小
    size_t size_all = size * nmemb;
    //3 开辟空间
    response_body->str = malloc(  size_all + 1);
    //4 拷贝数据
    memcpy( response_body->str, data, size_all);
    response_body->str[size_all] = '\0';
    response_body->len=size_all;
    return size_all;

}

/**
 * @brief ota http get访问方法
 *     //1 初始化curl
    //2 设置curl的参数 3个： url \  function \ 容器 writedata
    //3 执行
    //4 清理 
    //5 获取返回值
 */
response_body_t *ota_http_curl_get(char *url )
{
    //1 初始化curl
    CURL *curl = curl_easy_init();
    //2 设置curl的参数 3个： url \  function \ 容器 writedata
    if(curl)
    {
        curl_easy_setopt(curl, CURLOPT_URL, url);
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, ota_http_curl_cb);

        response_body_t *response_body= malloc(sizeof(response_body_t));
        curl_easy_setopt(curl, CURLOPT_WRITEDATA,  response_body);
        //3 执行
        CURLcode res= curl_easy_perform(curl);
        if(res != CURLE_OK)
        {
            perror("curl_easy_perform() failed:");
            return NULL;
        }
           //4 清理 
           curl_easy_cleanup(curl);
             //5 获取返回值
        return response_body;
    }
    return NULL;
 
  

}


/**
 * @brief ota http get访问方法  下载文件
 * @param url 访问地址
 * @param local_file_path 下载文件路径
 * @return 0 成功 非0 失败
 */
int ota_http_curl_download(char *url ,char *local_file_path )
{
        //1 初始化curl
        CURL *curl = curl_easy_init();
        //2 设置curl的参数 3个： url \  function \ 容器 writedata
        if(curl)
        {
            curl_easy_setopt(curl, CURLOPT_URL, url);
            curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, fwrite);
    
             FILE *fp = fopen(local_file_path, "wb");
            curl_easy_setopt(curl, CURLOPT_WRITEDATA,  fp); //容器指针
            //3 执行
            CURLcode res= curl_easy_perform(curl);
            if(res != CURLE_OK)
            {
                perror("curl_easy_perform() failed:");
                return -1;
            }
           //4 清理 
            fclose(fp);
            curl_easy_cleanup(curl);
            //5 获取返回值
            return 0;
        }
        return -1;
}